import {createRouter, createWebHistory} from 'vue-router'
import axios from 'axios'
import {ElMessage}  from "element-plus";

const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/Login.vue'),
        meta: {title: '登录'}
    },
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/Home.vue'),
        meta: {title: '首页'}
    },
    {
        path: '/about',
        name: 'about',
        component: () => import('@/views/About.vue'),
        meta: {title: '关于'}
    }


]

const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    if (to.path.startsWith('/login')) {
        //跳转到login路由, 移除token信息
        window.localStorage.removeItem('access-token')
        ElMessage.info('跳转到login页面, 移除了token信息')
        next()
    } else {
        let data = JSON.parse(window.localStorage.getItem('access-token'))
        console.log('data===>', data)
        if (!data) {
            console.log('token不存在, 跳转到login页面')
            ElMessage.error('token不存在, 跳转到login页面')
            next('/login')
        } else {
            axios.get('api/checkToken', {
                params: {
                    token: data.token
                }
            }).then(res => {
                console.log('router: res===>',res.data)
                if (res.data.code === 400) {
                    console.log('token失效')
                    ElMessage.error(res.data.msg)
                    next('/login')
                }
                console.log('执行下一步')
                next()
            })
        }
    }


    //next(); // 继续路由跳转
});
router.afterEach((to, from) => {
    document.title = to.meta.title || '佚名';
})
export default router;























